package user

import (
	"context"
	"github.com/axengine/utils/hash"
	"github.com/axengine/utils/random"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserResetPasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserResetPasswordLogic {
	return &UserResetPasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserResetPasswordLogic) UserResetPassword(req *types.UserResetPasswordRo) (resp *types.BaseRsp, err error) {
	var u model.User
	if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.Uid).First(&u).Error; err != nil {
		return
	}
	salt := random.RandAlphaAndDigits(8, true)
	hashedPswd := hash.Keccak256Base64([]byte(req.Password + salt))

	err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.Uid).
		Select("Salt", "Password").Updates(&model.User{

		Password: hashedPswd,
		Salt:     salt,
	}).Error

	return
}
